package org.luxor.commons.rabbitmq.context;

import org.luxor.commons.rabbitmq.definition.MessageDefinition;

import java.util.Stack;

/**
 * 管理将要发布的Rabbit消息
 *
 * @author Mr.yan @date 2019/10/17
 */
public final class MessageContext {
    private static final ThreadLocal<Stack<MessageDefinition>> MESSAGE_CONTEXT = new ThreadLocal<>();

    /**
     * 入栈
     */
    public static void push(MessageDefinition messageDefinition) {
        getStack(MESSAGE_CONTEXT).push(messageDefinition);
    }

    /**
     * 弹栈
     */
    public static Stack<MessageDefinition> getMessageDefintions() {
        return getStack(MESSAGE_CONTEXT);
    }

    /**
     * 清空上下文
     */
    public static void flush() {
        MESSAGE_CONTEXT.remove();
    }

    /**
     * 获取栈对象
     */
    private static <T> Stack<T> getStack(ThreadLocal<Stack<T>> threadLocal) {
        Stack<T> stack = threadLocal.get();
        if (stack == null) {
            stack = new Stack<T>();
            threadLocal.set(stack);
        }
        return stack;
    }
}
